package com.itany.controller;

import com.itany.entity.User;
import com.itany.vo.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户的API接口")
@RestController
@RequestMapping("/users")
public class UserController {

    // 模拟数据库
    static Map<Integer, User> users = new HashMap<>();
    static int id=1;

    @ApiOperation(value = "获取用户列表", notes = "获取所有用户信息")
    @GetMapping
    public ResponseResult getUserList(){
        // int i = 5/0;

        List<User> list = new ArrayList<>(users.values());

        User user = new User();
        user.setId(8001);
        list.add(user);

        return ResponseResult.success(list);
    }

    @ApiOperation(value = "获取指定用户", notes = "根据url中的id获取指定用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户编号", dataType = "Integer") // 分别表示：参数名、参数含义、参数类型、是否可以为空
    @GetMapping("/{id}")
    public ResponseResult getUser(@PathVariable Integer id){
        return ResponseResult.success(users.get(id));
    }

    @ApiOperation(value = "添加用户", notes = "根据User对象添加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PostMapping
    public ResponseResult postUser(User user){
        user.setId(id++);
        users.put(user.getId(), user);
        return ResponseResult.success();
    }

    @ApiOperation(value = "删除用户", notes = "根据url中的id删除指定用户")
    @ApiImplicitParam(name = "id", value = "用户编号", dataType = "Integer", required = true)
    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable Integer id){
        users.remove(id);
        return ResponseResult.success();
    }

    @ApiOperation(value = "修改用户", notes = "根据id修改指定用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true),
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PutMapping
    public ResponseResult putUser(User user){
        User u = users.get(user.getId());
        u.setUsername(user.getUsername());
        u.setPassword(user.getPassword());
        return ResponseResult.success();
    }

}
